package com.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mypg.Icon;

import com.service.IconService;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.StandardCharsets;

import java.text.ParseException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/icon")
@Controller
public class IconController {


    @Autowired
    IconService iconService;

    @RequestMapping("/icon_table_select.do")
    @ResponseBody
    public String doIcon_table_select(String icon_class,int page, int limit) throws ParseException, JsonProcessingException {
        int start_row=(page-1)*limit;
        int page_nums=limit;
        HashMap<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",iconService.selectIcon_count_For_icon_table_jsp(icon_class));
        List<Icon> iconList=iconService.selectIconFor_icon_table_jsp(icon_class,start_row,page_nums);
        map.put("data", iconList);
        ObjectMapper mapper=new ObjectMapper();
        String map_json_str=mapper.writeValueAsString(map);
        return map_json_str;
    }

    @RequestMapping("/icon_table_delete_one.do")
    @ResponseBody
    public void doNews_table_delete_one(int icon_id,HttpSession session){
        String path= (String) session.getAttribute("img_save_path");
        path+="/icon_img/";
        Icon icon=iconService.selectIconByIcon_id(icon_id);
        File file=new File(path+icon.getIcon_img());
        file.delete();
        iconService.deleteIconByIcon_id(icon_id);
    }

    @RequestMapping("/icon_table_delete_many.do")
    @ResponseBody
    public int doIcon_table_delete_many(String[] icon_id_array,HttpSession session){
        icon_id_array[0]=icon_id_array[0].replace("[","");
        icon_id_array[icon_id_array.length-1]=icon_id_array[icon_id_array.length-1].replace("]","");
        String path= (String) session.getAttribute("img_save_path");
        path+="/icon_img/";
        for(int i=0;i<icon_id_array.length;i++){
            Icon icon=iconService.selectIconByIcon_id(Integer.parseInt(icon_id_array[i]));
            File file=new File(path+icon.getIcon_img());
            file.delete();
            iconService.deleteIconByIcon_id(Integer.parseInt(icon_id_array[i]));
        }
        return 0;
    }

    @RequestMapping("/icon_table_add_with_file.do")
    @ResponseBody
    public Map<String,Object> doIcon_table_add_with_file(String icon_name, String icon_des, String icon_class,
                                                         @RequestParam(value="file_content",required = false) MultipartFile file_content,
                                                         @RequestParam(value="file_img",required = false) MultipartFile file_img,
                                                         HttpSession session){
        Icon icon=new Icon();
        String content_to_upload="";
        String img_to_upload="icon_img_default.jpg";

        if(file_content==null){
            content_to_upload=icon_des;
        }else{
            if(!file_content.isEmpty()){
                try {
                    InputStream in = file_content.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
                    int a = 0;
                    while((a = bufferedReader.read())!=-1){
                        char ch=(char)a;
                        content_to_upload+=ch;
                    }
                    in.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        if(file_img==null){
            img_to_upload="icon_img_default.jpg";
        }else{
            img_to_upload= UUID.randomUUID()+"_with_"+file_img.getOriginalFilename();
            String path= (String) session.getAttribute("img_save_path");
            path+="/icon_img/";
            if(!file_img.isEmpty()){
                try {

                    File uploadFile=new File(path+img_to_upload);
                    Streams.copy(file_img.getInputStream(),new FileOutputStream(uploadFile.getAbsolutePath()),true);


//                    FileOutputStream fos = new FileOutputStream(path + img_to_upload);
//                    InputStream in = file_img.getInputStream();
//                    int a = 0;
//                    while((a = in.read())!=-1){
//                        fos.write(a);
//                    }
//                    in.close();
//                    fos.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        icon.setIcon_class(icon_class);
        icon.setIcon_des(content_to_upload);
        icon.setIcon_img(img_to_upload);
        icon.setIcon_name(icon_name);
        iconService.insertIcon(icon);
        HashMap<String,Object> map=new HashMap<>();
        map.put("str",content_to_upload);
        return map;
    }

    @RequestMapping("/icon_table_edit.do")
    @ResponseBody
    public Map<String, Object> doIcon_table_edit(int icon_id, String icon_name, String icon_des, String icon_class,
                                                 @RequestParam(value="file_content",required = false) MultipartFile file_content) throws JsonProcessingException {
        String content_to_upload="";
        if(file_content==null){
            content_to_upload=icon_des;
        }else{
            if(!file_content.isEmpty()){
                try {
                    InputStream in = file_content.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
                    int a = 0;
                    while((a = bufferedReader.read())!=-1){
                        char ch=(char)a;
                        content_to_upload+=ch;
                    }
                    in.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        Icon icon=new Icon();
        icon.setIcon_id(icon_id);
        icon.setIcon_name(icon_name);
        icon.setIcon_des(content_to_upload);
        icon.setIcon_class(icon_class);
        iconService.updateIconByIcon_id(icon);
        HashMap<String,Object> map=new HashMap<>();
        map.put("str",content_to_upload);
        return map;
    }

    @RequestMapping("/icon_table_edit_init.do")
    @ResponseBody
    public Icon doIcon_table_edit_init(int icon_id){
        return iconService.selectIconByIcon_id(icon_id);
    }

    @RequestMapping("/icon_table_edit_upload_img.do")
    @ResponseBody
    public String doIcon_table_edit_upload_img(@RequestParam(value="file",required = false) MultipartFile file_img,
                                               HttpSession session, int icon_id) throws JsonProcessingException {
        HashMap<String, Object> map = new HashMap<>();
        if(session.getAttribute("flag_manager")!=null) {
            String img_to_upload = "";
            img_to_upload = UUID.randomUUID() + "_with_" + file_img.getOriginalFilename();
            String path = (String) session.getAttribute("img_save_path");
            path += "/icon_img/";
            String icon_img = iconService.selectIconByIcon_id(icon_id).getIcon_img();
            if (file_img != null) {
                if (!file_img.isEmpty()) {
                    File file = new File(path + icon_img);
                    file.delete();
                    try {

                        File uploadFile = new File(path + img_to_upload);
                        Streams.copy(file_img.getInputStream(), new FileOutputStream(uploadFile.getAbsolutePath()), true);


//                    FileOutputStream fos = new FileOutputStream(path + img_to_upload);
//                    InputStream in = file_img.getInputStream();
//                    int a = 0;
//                    while ((a = in.read()) != -1) {
//                        fos.write(a);
//                    }
//                    in.close();
//                    fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    iconService.updateIcon_imgByIcon_id(img_to_upload, icon_id);
                }

            }

            map.put("code", 0);
            map.put("msg", "");
            map.put("data", img_to_upload);
        }else{

            map.put("code", 0);
            map.put("msg", "");
            map.put("data", "fail");
        }
        return new ObjectMapper().writeValueAsString(map);
    }
}
